package com.Cfeng.XiaohuanChat.config;

import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;

/**
 * @author Cfeng
 * @date 2022/8/6
 * MongoDB数据库的存储记录
 */

@Configuration
public class MongoDBconfig {

    @Value("${spring.data.mongodb.database}")
    private String database;

    @Value("${spring.data.mongodb.uri}")
    private String uri;

    @Bean
    public MongoClient mongoClient() {
        ConnectionString connectionString = new ConnectionString(uri);
        //连接的uri创建Mongo客户端设置
        MongoClientSettings mongoClientSettings = MongoClientSettings.builder().applyConnectionString(connectionString).build();
        return MongoClients.create(mongoClientSettings);
    }
    //再创建MongoTemplate对象 【redisTemplate对象如果是Lettuce是自动配置了的，但是不管Lettuce还是Jedis可以手动配置修改参数】
    //使用上面的客户端和数据库名
    @Bean
    public MongoTemplate mongoTemplate() throws Exception {
        return new MongoTemplate(this.mongoClient(),database);
    }
}
